package com.group.exception;

import com.group.result.Result;
import com.group.result.ResultEnum;
import com.group.utils.JsonUtils;
import com.group.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * com.gxa.exception
 * User: 恩哲欣
 * Date: 2024/10/22 19:14
 * Motto: Where there is a will, there is a way!
 * Description:
 * Version: V1.0
 */
public class CustomerExceptionResolver implements HandlerExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(CustomerExceptionResolver.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String msg;
        Integer code;
        if (e instanceof CustomerException) {
            CustomerException customerException = (CustomerException) e;
            ResultEnum resultEnum = customerException.getResultEnum();
            msg = resultEnum.getMessage();
            code = resultEnum.getCode();
            logger.debug("自定义信息异常,code:{},message:{}",code,msg);
        }else if (e instanceof SQLIntegrityConstraintViolationException) {
            logger.error("数据操作异常:{}",e.getMessage());
            code = ResultEnum.OPTION_FAIL.getCode();
            msg = ResultEnum.OPTION_FAIL.getMessage();
        } else {
            logger.error("未知异常:{}",e.getMessage());
            code = ResultEnum.UNKNOWN_EXCEPTION.getCode();
            msg = ResultEnum.UNKNOWN_EXCEPTION.getMessage();
        }
        // 构建返回对象
        Result<Object> result = Result.buildFail(code,msg);
        // 返回JSON
        ResponseUtils.responseToJson(httpServletResponse, JsonUtils.objectToJson(result));
        return new ModelAndView();
    }
}
